<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- <link rel="stylesheet" href="../css/detail.css">
    <link rel="stylesheet" href="../css/ui-base.css"> -->
    <link rel="stylesheet" href="../css/goodsDetail.css">
    <script src="../js/jquery-3.6.0.min.js"></script>
    <script src="../js/api.js"></script>
    <script src="../js/cookie.js"></script>
    <style>
        input::-webkit-outer-spin-button,
        input::-webkit-inner-spin-button {
            -webkit-appearance: none;
        }

        input[type="number"] {
            -moz-appearance: textfield;
        }
		#wangyao{
			font-size: 100000000000000;
		}
    </style>
</head>

<body>
    <div class="box">
		<div id="wangyao">
			王瑶是傻逼
		</div>
        <a href="./login.html">你好,请登录</a>
        <a href="./register.html">注册</a>
    </div>
    <div class="wrap">
        <div class="left">

        </div>
        <div class="right">

        </div>
    </div>
    <div class="detailBox">

    </div>
</body>
<script>
    var cookie = document.cookie;
    if (cookie) {  // 标识用户身份
        var user = getCookie("lgc");
        if (user) {
            $(".box").html(`欢迎您,${user} <button onclick="exit()">退出</button>`);
        }
    }
    
    var search = location.search;
    if (search) {  //有gid数据 
        console.log(search);
        var gid = search.split("=")[1];
        console.log(gid);
        (async function () {

            let result = await searchGoodsById({ gid })
            console.log(result);

            var { status, data: { goodsName, goodsPrice, bigPicList, smallPicList } } = result;
            if (status) {  //有数据 (根据gid能查到数据);
                var leftHTML = `<div class="wrapBox">
                            <div class="shadow"></div>
                            <img class="small" src="${bigPicList[0]}" alt="">
                        </div>
                        <ul class="switchList">
                           
                        </ul>
                        <div class="showBigImg">
                            <img class="bigImg" src="${bigPicList[0]}" alt="">
                        </div>`

                $(".left").html(leftHTML);
               
                            

                var listHTML = "";
                var len = smallPicList.length;
                for (var i = 0; i < (len > 4 ? 4 : len); i++) {
                    var img = smallPicList[i];
                    listHTML += `<li><img src="${img}" bigUrl="${bigPicList[i]}" alt=""></li>`

                }
                $(".switchList").html(listHTML);
                $(".switchList li").eq(0).addClass("active");


                var rightHTML = `<h2>${goodsName}</h2>
            <div class="price">
                京 东 价:<span>￥</span> <span>${goodsPrice}</span> 降价通知
            </div>
            <span>配送至：</span>
            <select class="province">
                <option value="">请选择省份</option>
            </select>
            <select class="city">
                <option value="">请选择市区</option>
            </select>
            <select class="town">
                <option value="">请选择县区</option>
            </select>
            <div class="buyNum">
                <div>
                    <input class="count-input" type="number" value="1">
                    <span class="add">+</span>
                    <span class="reduce">-</span>
                </div>
                <button class="addToCar">
                加入购物车
                </button>
            </div>`
            
                $(".right").html(rightHTML);


                var wrapAll = $(".wrap")[0];
                var left = $(".wrapBox")[0];
                var right = $(".showBigImg")[0];
                var shadow = $(".shadow")[0];
                var smallImg = $(".small")[0];
                var bigImg = $(".bigImg")[0];
                var maxLeft = null;
                var maxTop = null;
                var scale = null;

                left.onmouseenter = function () {
                    shadow.style.display = "block";
                    right.style.display = "block";

                    // 等元素显示之后再取值
                    maxLeft = left.clientWidth - shadow.clientWidth;
                    maxTop = left.clientHeight - shadow.clientHeight;
                    // console.log(maxLeft, left.clientWidth, shadow.clientWidth);
                    scale = bigImg.clientWidth / smallImg.clientWidth;
                }
                left.onmouseleave = function () {
                    shadow.style.display = "none";
                    right.style.display = "none";
                }

                left.onmousemove = function (e) {
                    var e = e || window.event;
                    // console.log("moving");
                    var x = e.pageX - wrapAll.offsetLeft - shadow.clientWidth / 2;
                    var y = e.pageY - wrapAll.offsetTop - shadow.clientHeight / 2;

                    if (x < 0) x = 0;
                    if (x >= maxLeft) x = maxLeft;
                    if (y <= 0) y = 0;
                    if (y > maxTop) y = maxTop;

                    shadow.style.left = x + "px";
                    shadow.style.top = y + "px";

                    bigImg.style.left = -scale * x + "px";
                    bigImg.style.top = -scale * y + "px";

                }

                var province = document.getElementsByClassName("province")[0];
    var city = document.getElementsByClassName("city")[0];
    var town = document.getElementsByClassName("town")[0];
    var xhr = new XMLHttpRequest();

    xhr.open("get", "../data/proData.json", true);

    xhr.send();

    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var result = JSON.parse(xhr.responseText);
            // console.log(result);
            var { list: proList } = result;
            var html = `<option value="">请选择省份</option>`;
            proList.forEach(function (item) {
                var { city_id, name } = item;
                // <option value="">请选择省份</option>
                html += `<option value="${city_id}">${name}</option>`;
            })
            province.innerHTML = html;
            province.onchange = function () {
                var cityId = this.value;
                if (cityId) {
                    // console.log(cityId, proList);
                    var arr = proList.filter(function (item) {
                        return cityId == item.city_id;
                    });
                    var thisPro = arr[0];
                    // console.log(thisPro);
                    var { list: cityList } = thisPro;
                    var html = '<option value="">请选择市区</option>';
                    cityList.forEach(function (item) {
                        var { city_id, name } = item;
                        html += `<option value="${city_id}">${name}</option>`;
                    })
                    city.innerHTML = html;
                    town.innerHTML = `<option value="">请选择县区</option>`;
                    // town.style.display = "none";


                    city.onchange = function () {
                        var cityId = this.value;
                        if (cityId) {
                            // console.log(cityId, proList);
                            var arr = cityList.filter(function (item) {
                                return cityId == item.city_id;
                            });
                            var thisCity = arr[0];
                            // console.log(thisCity);
                            var { list: townList } = thisCity;
                            if (townList) {
                                town.style.display = "inline-block";
                                console.log(townList);
                                var html = '<option value="">请选择县区</option>';
                                townList.forEach(function (item) {
                                    var { city_id, name } = item;
                                    html += `<option value="${city_id}">${name}</option>`;
                                })
                                town.innerHTML = html;
                            } else {
                                town.style.display = "none";
                            }
                        } else {
                            town.innerHTML = '<option value="">请选择县区</option>';
                        }
                    }
                } else {
                    city.innerHTML = '<option value="">请选择市区</option>';
                    town.innerHTML = '<option value="">请选择县区</option>';
                }
            }
        }
    }

        } else {
            location.href = "./index.html";
        }

        })()
    } else {
        location.href = "./index.html";
    }

    $(document).on("click", ".switchList li", function () {
        $(this).addClass("active").siblings().removeClass("active");
        var url = $(this).find("img").attr("bigUrl");
        $(".bigImg,.small").prop("src", url);
    })

    $(document).on("click",".reduce",function(){
        var num = parseInt($(".buyNum input").val());
        if(num<=1){
            num = 2;
        }
        $(".buyNum input").val(num-1);
    })

    $(document).on("click",".add",function(){
        var num = parseInt($(".buyNum input").val());
        $(".buyNum input").val(num+1);
    })

    $(document).on("click", ".addToCar", async function () {
        console.log("点击加入购物车");

        // 加入购物车  需要知道的信息  
        // 谁?  买了什么东西 ?  买了多少件?
        // 谁?  => 当前登录的用户
        // 买了什么东西?   商品的编号(goodsId) 
        // 买了多少件?   val

        // 谁?   加入购物车之前判断用户是否登录
        var user = getCookie("lgc");  // 当前登录的用户
        console.log(user);
        if (user) {  //有用户登录  => 买
            var buyNum = $(".buyNum .count-input").val();
            console.log(buyNum);
            // addShoppingCar({ user, goodsId: gid, buyNum }).then().catch()

            var result = await addShoppingCar({ user, goodsId: gid, buyNum });
            console.log(result);
            var { status } = result;
            if (status) {
                if (confirm("购买成功,是否进入购物车?")) {
                    location.href = "./shoppingCar.html"
                }
            } else {
                alert("系统繁忙,请稍后...");
            }
        } else {  // 没有登录   => 去登录

            // 问题? 如何让用户登录之后 返回 当前页?
            // 把当前页的url(location.href)  作为一个参数 存储在returnUrl中?

            // 登录成功 就判断 有没有returnUrl => 有  =>  回去
            //                                  没有 => 进入主页

            location.href = "./login.html?returnUrl=" + encodeURIComponent(location.href);
        }


    })

    //省市三级联动
    

    function exit() {
        delCookie("lgc");
        location.reload();
    }

</script>

</html>